#include "myNodepad.h"

myNodepad::myNodepad(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
	this->setWindowTitle("我的nodepad++");
	this->setWindowIcon(QIcon(":/images/images/Qicon.jpg"));

	QObject::connect(ui.newAction, &QAction::triggered,
		this, &myNodepad::newActionSlot);
	QObject::connect(ui.openAction, &QAction::triggered,
		this, &myNodepad::openActionSlot);
	QObject::connect(ui.saveAction, &QAction::triggered,
		this, &myNodepad::saveActionSlot);
}

myNodepad::~myNodepad()
{}

void myNodepad::keyPressEvent(QKeyEvent * k)
{
	if (k->modifiers() == Qt::ControlModifier && k->key() == Qt::Key_S)
	{
		saveActionSlot();
	}
}

void myNodepad::mousePressEvent(QMouseEvent * m)
{
	QPoint pt = m->pos();
	qDebug() << pt;
	if (m->button() == Qt::LeftButton)
	{
		qDebug() << "左键被按下！";
	}
	else if (m->button() == Qt::RightButton)
	{
		qDebug() << "右边键被按下！";
	}
}

void myNodepad::newActionSlot()
{
	ui.textEdit->clear();
	this->setWindowTitle("新建文本文档");
}

void myNodepad::openActionSlot()
{
	this->setWindowTitle("请选择一个文件");
	QString fileName = QFileDialog::getOpenFileName(this, "请选择一个文件",
		QCoreApplication::applicationFilePath(), "*.txt");
	if (fileName.isEmpty())
	{
		QMessageBox::warning(this, "警告", "请选择一个文件!");
		this->setWindowTitle("我的nodepad++");
	}
	else
	{
		this->setWindowTitle(fileName);
		QFile file(fileName);
		file.open(QIODevice::ReadOnly);
		QByteArray ba = file.readAll();
		ui.textEdit->setText(QString(ba));
		file.close();
	}
}

void myNodepad::saveActionSlot()
{
	this->setWindowTitle("请选择一个文件");
	QString fileName = QFileDialog::getSaveFileName(this, "请选择一个文件",
		QCoreApplication::applicationFilePath());
	if (fileName.isEmpty())
	{
		QMessageBox::warning(this, "警告", "请选择一个文件");

	}
	else
	{
		QFile file(fileName);
		file.open(QIODevice::WriteOnly);
		QByteArray ba;
		ba.append(ui.textEdit->toPlainText());
		file.write(ba);
		file.close();
	}
	this->setWindowTitle("我的nodepad++");
}

